import { resolve } from 'path'
import { babel } from '@rollup/plugin-babel'
import typescript from 'rollup-plugin-typescript2'
import nodeResolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import json from '@rollup/plugin-json'
import alias from '@rollup/plugin-alias'
import copy from 'rollup-plugin-copy'
import dts from 'rollup-plugin-dts'
import pkg from './package.json'
import { terser } from 'rollup-plugin-terser'

function pathResolve(dir) {
  return resolve(process.cwd(), '.', dir)
}

// 打包 cjs => node esm => es module iife => 浏览器
const name = pkg.name
const outputConfigs = {
  'esm-bundler': {
    file: pathResolve(`dist/${name}.esm-bundler.js`),
    format: 'esm',
    exports: 'named',
    preferConst: true // 用 const 替换 var
  },
  cjs: {
    file: pathResolve(`dist/${name}.cjs.js`),
    format: 'cjs',
    exports: 'default'
  },
  global: {
    file: pathResolve(`dist/${name}.global.js`),
    format: 'iife',
    name: '$pollApi'
  }
}

const defaultFormats = ['esm-bundler', 'cjs', 'global']

const packageConfigs = defaultFormats.map(format => {
  let browser = true
  if (format === 'cjs') {
    browser = false
  }
  const plugins = [
    json(),
    alias({
      entries: [
        // @/xxxx => src/xxxx
        {
          find: /@\//,
          replacement: pathResolve('src') + '/',
        },
        // #/xxxx => types/xxxx
        {
          find: /#\//,
          replacement: pathResolve('types') + '/',
        },
      ]
    }),
    typescript(), // 处理 ts 文件
    nodeResolve({browser: browser}), // 处理 引入第三方库
    commonjs(), // 将 cmd 规范的代码 转换为 es6 语法 这个要放到 babel 前面
    babel({
      babelHelpers: 'bundled',
      exclude: 'node_modules/**'
    }), // 兼容低 js 版本
    terser(), // 压缩输出包
    copy({
      targets: [
        { src: ['package.json', 'readme.md', 'README.zh_CN.md'], dest: 'dist' },
      ]
    })
  ]
  return createConfig(format, outputConfigs[format], plugins)
})

packageConfigs.push({
  input: pathResolve('./src/index.ts'),
  output: {
    file: pathResolve('dist/index.d.ts'),
    format: 'es'
  },
  plugins: [
    dts()
  ]
})

function createConfig(format, output, plugins) {
  return {
    input: pathResolve('./src/index.ts'),
    output,
    plugins: [
      ...plugins
    ]
  }
}

export default packageConfigs